package cn.t.web.order;

import cn.t.constants.ResponseError;
import cn.t.core.exception.BizException;
import cn.t.core.mode.PageInfoDTO;
import cn.t.core.mode.PageQueryDTO;
import cn.t.dto.order.OrderQueryRequest;
import cn.t.dto.order.OverPickupOrderDTO;
import cn.t.dto.order.excelresp.OverPickupOrderExcelResp;
import cn.t.facade.order.OverPickupRecordFacade;
import cn.t.listener.CustomCellWriteWidthConfig;
import cn.t.utils.ExcelUtil;
import com.alibaba.excel.EasyExcel;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import java.util.List;

/**
 * 超领记录表服务入口
 *
 * @author t
 * @since 2024-05-24 10:15:14
 */
@Slf4j
@RestController
@RequestMapping("overPickupRecord")

@AllArgsConstructor
public class OverPickupRecordController  {
    @Resource
    private OverPickupRecordFacade overPickupRecordFacade;
    /**
     * 超领列表查询
     */
    @PostMapping(value = "/listPage")
    public PageInfoDTO<OverPickupOrderDTO> findSkuByPage(@RequestBody PageQueryDTO<OrderQueryRequest> req) {
        return overPickupRecordFacade.overPickupRecord(req);
    }

    /**
     * 导出超领列表
     */
    @PostMapping(value = "exportOverPickupOrder")
    public void exportList(@RequestBody OrderQueryRequest req, HttpServletResponse response) {
        List<OverPickupOrderDTO> overPickupOrderList = overPickupRecordFacade.exportList(req);
        if (ObjectUtils.isEmpty(overPickupOrderList)) {
            throw new BizException(ResponseError.EXCEL_EMPTY, ResponseError.EXCEL_EMPTY.getName());
        }
        try {
            ExcelUtil.setHeader(response,  URLEncoder.encode("超领列表", "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            log.warn("导出超领列表异常 {}",e.getMessage());
            throw new BizException(ResponseError.EXCEL_EXPORT_ERR, ResponseError.EXCEL_EXPORT_ERR.getName());
        }
        // 执行导出
        try( ServletOutputStream outputStream = response.getOutputStream();) {

            EasyExcel.write(outputStream, OverPickupOrderExcelResp.class).sheet("超领列表").registerWriteHandler(new CustomCellWriteWidthConfig()).doWrite(overPickupOrderList);
        } catch (Exception e) {

            log.warn("导出超领列表异常 {}",e.getMessage());
            throw new BizException(ResponseError.EXCEL_EXPORT_ERR, ResponseError.EXCEL_EXPORT_ERR.getName());
        }
    }
}

